<?php

namespace App\Http\Controllers;

use App\Good;
use App\Order;
use Godruoyi\Snowflake\Snowflake;
use Illuminate\Http\Request;
use OSS\OssClient;
use OSS\Core\OssException;
use Yansongda\Pay\Pay;
use Yansongda\Pay\Log;


class GoodController extends Controller
{
    protected $config = [
        'app_id' => '2021000117606333',
        'notify_url' => 'http://yansongda.cn/notify.php',
        'return_url' => 'http://www.month2.com:8888/return',
        'ali_public_key' => 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAtQjZhJvM+FfbtaUKkZkZo+rtTtNcCuZNqEVs1wdxaymv0o+UbNWo0HnzkzEiczLkFBQ/hK1045cRgFV+lNHS4wAz07R/XNOM8wyOuBf1ViqKB/947cSFnZJAk8vi5EbehzK5fygPeGpwzfINu7y4UlQBNTmN2jtB3XS69niiDoCj3DbfeJaiY9rdi85BwRWk75hv19zAlGtVOLVrMg0L0KNP2O6D260vx/Vv2uEkOsXO5wjOTxnsAkyKkpSDPW17xASXsJNkkxZ/gkkChvl6AcIuBN5kuO4BWTR3kziTEG/U1srMM10E4UeYCgnQvP55/8CvbJi0tzh3uO35h2ArYwIDAQAB',
        // 加密方式： **RSA2**
        'private_key' => 'MIIEpAIBAAKCAQEAlBdDsEh9AHqVUsJNe5Z8dmD3nALLfoYDCd6brDsU2gd/Ou9kIRLLqRAoCv7p1aEk30yLDlK8EipkoSqhq1mp0sz7WNePGuAOWklRNqMEJs3aLixzpldqkpe6If7PFGk1ADUpmFvlQfh8qFH3KTFd8gle9JML7ED3FvZTDgRnM5ZUmjCS/qjcn3a3QGT1VJNB0sokA6ddztyyhnDXuYnMUVHcLRvZF3FLkFtTx7cKWUzfTDgK74lLbLCNQnNIkcS03Q2ndys9SgRigrTa0m2Cfc6K6JuSckJsUtOyiKfYktXWAjiQugV+i0Z+59C5JXPn7qU/hEBWDz34WPUUUNFaYQIDAQABAoIBAFYJ3i3BL77jeXYHpXS0TcOJOtLNXOU5fvJw/wjlmovB502aYBZHEUQ8Ose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BNmnd5AF8qv2UhKTqtG8IisRLQGNCP+m+8x7mDPjDbxDoqpj8g0b6diE/hWhDeOx/LjY3toWKYkLm4nkSX5Wy9fKSC1hHrWGgSde+XuFS0RA==',
        'log' => [ // optional
            'file' => './logs/alipay.log',
            'level' => 'info', // 建议生产环境等级调整为 info，开发环境为 debug
            'type' => 'single', // optional, 可选 daily.
            'max_file' => 30, // optional, 当 type 为 daily 时有效，默认 30 天
        ],
        'http' => [ // optional
            'timeout' => 5.0,
            'connect_timeout' => 5.0,
            // 更多配置项请参考 [Guzzle](https://guzzle-cn.readthedocs.io/zh_CN/latest/request-options.html)
        ],
        'mode' => 'dev', // optional,设置此参数，将进入沙箱模式
    ];

    public function pay(Request $request)
    {
        $params = $request->input();
        $order = [
            'out_trade_no' => $params['out_trade_no'],
            'total_amount' => $params['total_amount'],
            'subject' => $params['subject'],
            'timeout_express'=>'30m'
        ];

        $alipay = Pay::alipay($this->config)->web($order);

        return $alipay;// laravel 框架中请直接 `return $alipay`
    }

    public function return()
    {
        $data = Pay::alipay($this->config)->verify(); // 是的，验签就这么简单！
        try {
            Order::where('order_no',$data->out_trade_no)->update(['status'=>1]);
        }catch (\Exception $e){
            return $e->getMessage();
        }

        // 订单号：$data->out_trade_no
        // 支付宝交易号：$data->trade_no
        // 订单总金额：$data->total_amount
    }



    public function notify()
    {
        $alipay = Pay::alipay($this->config);

        try{
            $data = $alipay->verify(); // 是的，验签就这么简单！

            // 请自行对 trade_status 进行判断及其它逻辑进行判断，在支付宝的业务通知中，只有交易通知状态为 TRADE_SUCCESS 或 TRADE_FINISHED 时，支付宝才会认定为买家付款成功。
            // 1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号；
            // 2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额）；
            // 3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）；
            // 4、验证app_id是否为该商户本身。
            // 5、其它业务逻辑情况

            Log::debug('Alipay notify', $data->all());
        } catch (\Exception $e) {
            // $e->getMessage();
        }

        return $alipay->success()->send();// laravel 框架中请直接 `return $alipay->success()`
    }







    public function create()
    {
        return view('create');
    }

    public function todo($string)
    {
        $list = ['傻', '日', '性'];
        $pattern = "/" . implode("|", $list) . "/i";
        if (preg_match_all($pattern, $string, $matches)) {
            $patternlist = $matches[0];
            $replaceArray = array_combine($patternlist, array_fill(0, count($patternlist), '*'));
            foreach ($replaceArray as $key => $value) {
                $string = str_replace($key, $value, $string);
            }
        }
        return $string;
    }

    public function oss($filepath){
// 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录RAM控制台创建RAM账号。
        $accessKeyId = "LTAI4G3N1S4pMrVNx77dSA7v";
        $accessKeySecret = "w2WPCRxM1xnL7q9XZDyd9zGM3w1nKf";
// Endpoint以杭州为例，其它Region请按实际情况填写。
        $endpoint = "http://oss-cn-shanghai.aliyuncs.com";
// 设置存储空间名称。
        $bucket= "bliuce";
// 设置文件名称。
        $object = rand(1000,9999).'.jpg';
// <yourLocalFile>由本地文件路径加文件名包括后缀组成，例如/users/local/myfile.txt。
        $filePath = $filepath;

        try{
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);

            $ossClient->uploadFile($bucket, $object, $filePath);
        } catch(OssException $e) {
            printf(__FUNCTION__ . ": FAILED\n");
            printf($e->getMessage() . "\n");
            return;
        }
      $url = $this->getUrl($object);
        return $url;
    }

    public function getUrl($object){
        $str=base64_encode('正确归因');
        $suffix="image/resize,w_150,h_150/watermark,type_d3F5LXplbmhlaQ,size_30,text_$str,color_FFFFFF,shadow_50,t_100,g_se,x_10,y_10";
        $accessKeyId = "LTAI4G3N1S4pMrVNx77dSA7v";
        $accessKeySecret = "w2WPCRxM1xnL7q9XZDyd9zGM3w1nKf";
// Endpoint以杭州为例，其它Region请按实际情况填写。
        $endpoint = "https://oss-cn-shanghai.aliyuncs.com";
        $bucket= "bliuce";
        $object = $object;

        $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);

// 生成一个带图片处理参数的签名的URL，有效期是3600秒，可以直接使用浏览器访问。
        $timeout = 3600*24;
        $options = array(
            OssClient::OSS_PROCESS => "$suffix" );
        $signedUrl = $ossClient->signUrl($bucket, $object, $timeout, "GET", $options);
        return $signedUrl;
    }


    public function save(Request $request)
    {
        $params = $request->all();
        $good_name = $this->todo($params['goods_name']);
        unset($params['goods_name']);
        $params['goods_name'] = $good_name;
        $filepath =$request->file('file')->getPathname();
        $url = $this->oss($filepath);
        unset($params['file']);
        $params['pic']=$url;
        $time = time();
        $start = strtotime($params['start_time']);
        $end = strtotime($params['end_time']);
        if ($time<$end && $start <$time){
            $params['status']='正在进行';
        }elseif ($time < $start){
            $params['status']='未开始';
        }elseif ($time >$end){
            $params['status']='已结束';
        }
        Good::create($params);
    }

    public function index(){
        $data = Good::all();
        return view('index',['data'=>$data]);
    }

    public function show(){
        $data = Good::where('status','正在进行')->get();
        return view('show',['data'=>$data]);
    }

    public function detail(Request $request){
        $model = Good::find(2);
        return view('detail',['model'=>json_decode(json_encode($model),true)]);
    }


}
